<?php

/**
 * Created by PhpStorm.
 * User: xuzhong
 * Date: 2025/4/2
 * Time: 13:49
 */

declare(strict_types=1);

namespace app\admin\service;

use app\admin\common\ServiceResponse;
use app\admin\model\Article as ArticleModel;
use app\admin\model\Images;
use think\facade\Db;

class Article extends BaseService
{
    use ServiceResponse;

    protected $model;

    public function __construct()
    {
        $this->model = new ArticleModel();
        parent::__construct();
    }

    /**
     * @describe 获取销售人员列表
     * @author: 徐众
     * @date: 2025-04-02 13:02:26
     * @param [] type
     * @return Renderable
     */
    public function getList($keywords, $page, $limit,$params): array
    {
        if (0 >= $page || 100 < $limit) {
            return $this->error(100002);
        }
        $where = ['is_del' => 0];
        $sql = $this->model->where($where);
        if ($keywords) {
            $sql = $sql->whereRaw(
                "title like ? or content like ? ",
                ['%' . $keywords . "%", '%' . $keywords . "%"]
            );
        }
        if(isset($params['type']) && $params['type']){
            $sql = $sql->where('type',$params['type']);
        }
        if(isset($params['category']) && $params['category']){
            $sql = $sql->where('category',$params['category']);
        }
        if(isset($params['create_time']) && $params['create_time']){
            $range = explode(',',$params['create_time']);
            $start = $range[0] ?? '';
            $end = $range[1] ?? '';
            if($start){
                $sql = $sql->where('create_time','>=',$start." 00:00:00");
            }
            if($end){
                $sql = $sql->where('create_time','<=',$end." 23:59:59");
            }
        }
        $total = $sql->count();
        if (!$total) {
            return $this->success(['list' => [], 'total' => 0]);
        }
        $list = $sql->page($page, $limit)->order('id DESC')->select()->toArray();
        $photoId = array_unique(array_column($list, 'photo'));
        $photoId = array_unique(array_column($list, 'photo'));
        // 获取所有pids字段
        $pidsArray = array_column($list, 'pids');

        // 处理逗号分隔的字符串，合并为一维数组
        $allPids = [];
        foreach ($pidsArray as $pidsString) {
            if (!empty($pidsString)) {
                // 将逗号分隔的字符串拆分为数组
                $splitPids = explode(',', $pidsString);
                // 合并到总数组中
                $allPids = array_merge($allPids, $splitPids);
            }
        }

        // 去重、过滤空值、转换为整数
        $pids = array_unique(array_filter(array_map('intval', $allPids)));

        // 重新索引数组（可选）
        $pids = array_values($pids);
        $product = Db::name('product')->where('id', 'in', $pids)->field('id,cname,pid')->select()->toArray();
        $product = array_column($product, 'cname', 'id');

        #获取图片url
        $oImages = new Images();
        $photoUrls = $oImages->getImagesByIds($photoId);
        $avatorUrls = array_column($photoUrls, null, 'id');
        #替换url
        foreach ($list as $k => $v) {
            $list[$k]['photoUrl'] = $avatorUrls[$v['photo']]['url'] ?? '';
            $list[$k]['name'] = $avatorUrls[$v['photo']]['name'] ?? '';
            $list[$k]['photoId'] = $avatorUrls[$v['photo']]['id'] ?? '';

            if ($v['pids']) {
                $pids = explode(',', $v['pids']);
                $pids_name = [];
                foreach ($pids as $pid) {
                    $pids_name[] = $product[$pid] ?? '';
                }
                $list[$k]['pids_name'] = implode(',', $pids_name);
            } else {
                $list[$k]['pids_name'] = '';
            }
        }

        return $this->success(['list' => $list, 'total' => $total]);
    }
    /**
     * 创建
     * @param array $data 创建数据
     */
    public function create($data)
    {
        if (isset($data['category']) && !$data['category']) {
            if ($data['category'] == 7 && (!isset($data['pid']) || !$data['pids'])) {
                return $this->error(100001, '请选择关联矿机');
            }
            unset($data['category']);
        }
        if (!empty($data)) {
            try {
                $res = $this->model->create($data);
                if ($res) {
                    $this->logger->logOperation($res->id, 'Article', '创建', '创建文章');
                    return $this->success();
                } else {
                    return $this->error(500001);
                }
            } catch (\Throwable $th) {
                return $this->error(500001, '服务器内部错误：' . $th->getMessage());
            }
        } else {
            return $this->error(500001, '服务器内部错误');
        }
    }
    /**
     * 获取文章详情
     * @param int $id 文章ID
     */
    public function getOneById($id)
    {
        $article = $this->model->find($id);
        if ($article) {
            $data = $article->append(['creator_value']);
        }
        $data = $data->toArray();
        return $this->success($data);
    }
    /**
     * 更新销售人员
     * @param int $id 物流公司ID
     * @param array $data 更新物流公司的数据
     */
    public function update($data)
    {
        if (isset($data['category']) && !$data['category']) {
            $data['category'] = null;
        }
        $res = $this->model->where('id', $data['id'])->find();
        if (!$res) {
            return false;
        }
        foreach ($data as $key => $value) {
            if ($res->$key != $value) {
                $res->$key = $value;
            }
        }
        $result = $res->save();
        if ($result) {
            $this->logger->logOperation($res->id, 'Article', '更新', '更新文章');
            return $this->success();
        } else {
            return $this->error(500001);
        }
    }

    /**
     * @describe 删除销售人员
     * @author: 徐众
     * @date: 2025-04-02 13:02:26
     * @param [] type
     * @return Renderable
     */
    public function delete($param): array
    {
        #校验参数
        if (!isset($param['ids']) || empty($param['ids'])) {
            return $this->error(100001, '操作失败');
        }
        #查询数据是否存在
        $result = $this->model->where('id', 'in', $param['ids'])->where('is_del', '=', 0)->select()->toArray();

        if (!empty($result)) {
            #更新记录
            $update = $this->model->where('id', 'in', $param['ids'])->where('is_del', '=', 0)->update([
                'is_del' => time()
            ]);
            if ($update) {
                #尝试记录操作日志 不影响主流程
                try {
                    $this->logger->logOperation($param['ids'], 'Article', '删除', '删除文章');
                } catch (\Exception $e) {
                    #记录日志或其他操作
                }
                return $this->success();
            } else {
                return $this->error(500001, '操作失败');
            }
        } else {
            #未找到记录返回失败
            return $this->error(400000, '未找到相关数据');
        }
    }

    /**
     * @describe
     * @author: Bobo
     * @date: 2025-02-13 11:03:36
     * @param [type] @required
     * @return Renderable
     */
    public function getFieldEnum($field = 'all')
    {
        $res = $this->model->getFieldEnum($field);
        return [
            'code' => 0,
            'data' => $res
        ];
    }
}
